<template>
    <el-row>
        <!-- 班级列表 -->
        <el-col :span="5">
            <h3 style="text-align: center;">班级列表</h3>
            <!-- props默认字段名为label -->
            <el-tree ref="classTreeRef" node-key="classId" highlight-current :data=classList
                :props="{ label: 'className' }" @node-click="handleNodeChange"></el-tree>
        </el-col>
        <!-- 学生管理 -->
        <el-col :span="18" :offset="1">
            <!-- 筛选 -->
            <el-form ref="queryFormRef" :model="queryForm" inline size="mini">
                <el-form-item label="学号" prop="stuNum">
                    <el-input v-model="queryForm.stuNum"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="stuName">
                    <el-input v-model="queryForm.stuName"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="queryForm.phone"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button type="info" @click="formRest('queryForm'), getStuList()">重置</el-button>
                </el-form-item>
                <!-- 添加 -->
                <el-row>
                    <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">添加</el-button>
                </el-row>
                <!-- 表格 -->
                <el-table :data="stuTableData" style="width: 100%">
                    <el-table-column type="index" label="#" align="center" fixed></el-table-column>
                    <el-table-column prop="stuNum" label="学号" show-overflow-tooltip align="center" width="100"
                        fixed></el-table-column>
                    <el-table-column prop="stuName" label="姓名" show-overflow-tooltip align="center"
                        fixed></el-table-column>
                    <el-table-column prop="majorId" label="专业" align="center" width="140">
                        <template #default="{ row }">
                            {{ transformMajor(row.majorId) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="phone" label="手机" show-overflow-tooltip align="center"
                        width="140"></el-table-column>
                    <el-table-column prop="age" label="年龄" align="center"></el-table-column>
                    <el-table-column prop="sex" label="性别" align="center">
                        <template #default="{ row }">
                            {{ transformSex(row.sex) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="110" show-overflow-tooltip
                        align="center"></el-table-column>
                    <el-table-column prop="updateTime" label="修改时间" width="110" show-overflow-tooltip
                        align="center"></el-table-column>
                    <!-- 编辑 -->
                    <el-table-column label="操作" width="200" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button type="text" icon="el-icon-edit-outline" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="text" icon="el-icon-delete" @click="handleDel(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-row style="margin-top: 10px;" type="flex" justify="center">
                    <el-pagination layout="prev, pager, next" :total="pagination.total" :page-size="pagination.pageSize"
                        :current-page.sync="pagination.pageNum" @current-change="getStuList"></el-pagination>
                </el-row>

            </el-form>
        </el-col>
        <!-- 弹窗 -->
        <el-dialog :before-close="handleClose" :visible="dialog.visible" width="400px" @close="formRest('dialogForm')">
            <template #title>
                {{ dialog.mode == 'add' ? '添加学生' : '编辑学生信息' }}
            </template>
            <el-form ref="dialogFormRef" label-width="80px" label-position="top" size="small" :rules="dialog.rules"
                :model="dialog.form">
                <el-form-item label="名称" prop="classId">
                    <!-- 禁用的话不能用v-model,要用单向的普通数据绑定:value -->
                    <el-select :value="dialog.form.classId" disabled>
                        <el-option v-for="item in classList" :key="item.classId" :value="item.classId"
                            :label="item.className">{{ item.className }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="姓名" prop="stuName">
                    <el-input v-model="dialog.form.stuName"></el-input>
                </el-form-item>
                <el-form-item label="学号" prop="stuNum">
                    <el-input v-model="dialog.form.stuNum"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="dialog.form.phone"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="dialog.form.sex">
                        <el-option v-for="item in dictList" :key="item.dictValue" :value="item.dictValue"
                            :label="item.dictLabel">{{ item.dictLabel }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="专业" prop="majorId">
                    <el-select v-model="dialog.form.majorId">
                        <el-option v-for="item in majorList" :key="item.majorId" :value="item.majorId"
                            :label="item.majorName">{{ item.majorName }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input-number v-model="dialog.form.age" :min="1"></el-input-number>
                </el-form-item>
            </el-form>
            <el-row type="flex" justify="center" style="margin-top: 40px;">
                <el-button type="primary" size="small" @click="handleSubmit">确认</el-button>
                <el-button size="small" @click="handleClose">取消</el-button>
            </el-row>
        </el-dialog>
    </el-row>
</template>
<script>
import { listClasses } from '@/api/classes.js'
import { listStu, listMajor, addStudent, editStudent, delStudent } from '@/api/student.js'
import { listDict } from '@/api/common.js'
import { query } from '@/utils/common.js'
export default {
    name: 'Student',
    data() {
        return {
            // 班级列表
            classList: [],
            // 筛选
            queryForm: {
                stuNum: undefined,
                stuName: undefined,
                phone: undefined,

            },
            // 学生表格
            stuTableData: [],
            // 当前的班级信息
            curClasses: {},
            // 分页
            pagination: {
                pageNum: 1,
                pageSize: 10,
                total: 0,
            },
            // 专业
            majorList: [],
            // 性别
            dictList: [],
            // 弹窗
            dialog: {
                mode: 'add', //更换模式
                visible: false,
                form: {
                    "classId": undefined,
                    "stuName": undefined,
                    "stuNum": undefined,
                    "phone": undefined,
                    "sex": undefined,
                    "majorId": undefined,
                    "age": undefined
                },
                rules: {
                    classId: [{ required: true, message: '请输入班级', trigger: 'blur' }],
                    stuName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
                    stuNum: [{ required: true, message: '请输入学号', trigger: 'blur' }],
                    phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
                    sex: [{ required: true, message: '请输入性别', trigger: 'blur' }],
                    majorId: [{ required: true, message: '请输入专业', trigger: 'blur' }],
                    age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
                }
            }
        }
    },
    computed: {
        //   转换专业
        transformMajor() {
            return code => {
                const { majorName } = this.majorList.find(item => item.majorId === code) || {}
                return majorName || '-'
            }
        },
        // 转换性别
        transformSex() {
            return sexCode => {
                const { dictLabel } = this.dictList.find(item => item.dictValue == sexCode) || {}
                return dictLabel || '-'
            }
        }
    },
    created() {
        this.getClassesList()
        this.getMajorList()
        this.getListDict()
    },
    methods: {
        // 获取班级列表
        getClassesList() {
            listClasses().then(res => {
                this.classList = res.data
                console.log(this.classList)
                if (res.data.length > 0) {
                    // 存储当前第一条的班级信息
                    this.curClasses = res.data[0]
                    this.dialog.form.classId = res.data[0].classId
                    this.getStuList()
                    // $nextTick()等页面加载完毕之后再执行里面的逻辑
                    this.$nextTick(() => {
                        this.$refs['classTreeRef'].setCurrentKey(res.data[0].classId)
                    })

                }

            })
        },
        // 获取学生列表
        getStuList(query = {}) {
            const { classId } = this.curClasses
            const { total, ...res } = this.pagination
            listStu({ ...res, classId, ...query }).then(res => {
                this.stuTableData = res.data.rows
                // 更新学生总数
                this.pagination.total = res.data.count
                console.log(res)
            })
        },
        // 获取专业列表
        getMajorList() {
            listMajor().then(res => {
                this.majorList = res.data
            })
        },
        // 获取性别列表
        getListDict() {
            listDict('sys_user_sex').then(res => {
                console.log(res)
                this.dictList = res.data
                console.log(this.dictList)
            })
        },
        // 点击节点
        handleNodeChange(data, node, cpn) {
            this.curClasses = JSON.parse(JSON.stringify(data))
            this.getStuList()
            this.dialog.form.classId = data.classId
        },
        // 查询
        handleQuery() {
            const hasInput = query(this.queryForm)
            // 每一项不符合
            if (!hasInput) return this.$message.warning("没有输入值，请至少输入一项!")

            // 符合
            this.getStuList(this.queryForm)

        },
        // 重置
        formRest(val) {
            this.$refs[`${val}Ref`].resetFields()
        },
        // 添加
        handleAdd() {
            this.dialog.visible = true
            // 更换弹窗模式
            this.dialog.mode = 'add'
        },
        // 编辑
        handleEdit(row) {
            this.dialog.visible = true
            // 更换弹窗模式
            this.dialog.mode = 'edit'
            // 等dom渲染完毕之后再更新数据
            this.$nextTick(() => {
                // 浅拷贝:新旧数据之间相互影响
                // 深拷贝：数据独立，不会被影响
                this.dialog.form = JSON.parse(JSON.stringify(row))
                console.log(this.dialog.form)
            })
        },
        // 删除
        handleDel(row) {
            console.log(row)
            this.$confirm(`是否删除该班【${row.classInfo.className}】的学生【${row.stuName}】?`, '系统提示', {
                type: 'warning'
            }).then(() => {
                delStudent(row.stuId).then(res => {
                    this.$message.success(res.msg)
                    this.getStuList()
                })
            })
                .catch(() => { })
        },
        // 提交
        handleSubmit() {
            this.$refs['dialogFormRef'].validate(async value => {
                console.log(value)
                // 校验不通过
                if (!value) return
                // 校验通过
                // 传递参数的时候过滤信息
                const { classInfo, createTime, updateTime, stuId, ...rest } = this.dialog.form
                let result = {}
                try {

                    switch (this.dialog.mode) {
                        case 'add':
                            result = await addStudent({ ...rest })
                            break
                        case 'edit':
                            result = await editStudent({ ...rest, stuId })
                            break
                    }

                } catch (error) {

                }
                this.$message.success(result.msg)
                // 更新学生信息
                this.getStuList()
                // 关闭弹窗
                this.dialog.visible = false
                // 清空表单
                this.formRest('dialogForm')

            })
        },
        // 取消
        handleClose() {
            this.dialog.visible = false

            // 清空表单
            this.formRest('dialogForm')
        },


    }
}
</script>
<style scoped>
.el-row {
    margin-bottom: 20px;


}

.el-col {
    border-radius: 4px;
}

.bg-purple-dark {
    background: #99a9bf;
}

.bg-purple {
    background: #d3dce6;
}

.bg-purple-light {
    background: #e5e9f2;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}

.row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
}
</style>